package com.fhj.bookshop.controller;

import cn.hutool.core.util.RandomUtil;
import com.fhj.bookshop.common.R;
import com.fhj.bookshop.utils.AliOssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Random;

@RestController
public class FileController {
    @Autowired
    private AliOssUtils aliOssUtils;

    public static final String USER_AVATAR_DIRECTORY_NAME = "fImage";
    public static final String PRODUCT_IMAGE_DIRECTORY_NAME = "fPicture";

    @PostMapping("/uploadProImg")
    public  R uploadProImg(MultipartFile file) throws Exception{
        String url=uploadFile(file,PRODUCT_IMAGE_DIRECTORY_NAME);
        if(url==""){
            return R.error("上传错误");
        }
        else{
            return R.ok("上传商品图片成功").setData(url);
        }
    }

    @PostMapping("/uploadAvatar")
    public  R uploadAvator(MultipartFile file) throws Exception{
        String url=uploadFile(file,USER_AVATAR_DIRECTORY_NAME);
        if(url==""){
            return R.error("上传错误");
        }
        else{
            return R.ok("上传头像成功").setData(url);
        }
    }


    private String uploadFile(MultipartFile file, String directoryName) throws Exception{
        String originalFilename =file.getOriginalFilename();
        if (originalFilename == null) {
            return "";
        }
        String filename = RandomUtil.randomString(5) + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName =directoryName+"/"+filename;

        String url = aliOssUtils.uploadFile(objectName,file.getInputStream());
        return url;
    }
}
